package com.controller;

import com.Table.Movie;
import com.model.operation.MovieOperate;
import com.model.operation.UserOperate;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * Created by LPFma on 2016/12/5 0005.
 */
@WebServlet(name = "AddCoinHistory", urlPatterns = "/AddCoinHistory")
public class AddCoinHistory extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*init response*/
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.addHeader("Access-Control-Allow-Origin","*");
        response.addHeader("Access-Control-Allow-Credentials", "true");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        String username = (String) request.getSession().getAttribute("username");
        String num = request.getParameter("num");
        String pages = request.getParameter("pages");

        UserOperate userOperate = new UserOperate();
        ArrayList<Movie> movieArrayList =
                userOperate.CheckUserAddCoinHistory(username, Integer.valueOf(num), Integer.valueOf(pages));

        JSONArray jsonArray = new JSONArray();
        for(Movie movie : movieArrayList){
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("movieID", movie.getMovieID());
                jsonObject.put("moviename", movie.getMoviename());
                jsonObject.put("address", movie.getAddress());
                jsonObject.put("picture", movie.getPicture());
                jsonObject.put("tag", movie.getTag());
                jsonObject.put("descrition", movie.getDescription());
                jsonObject.put("coinnum", movie.getCoinnum());

                jsonArray.put(jsonObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        JSONObject jsonObjAmount = new JSONObject();
        try {
            jsonObjAmount.put("num", movieArrayList.size());
            jsonObjAmount.put("pages", Integer.valueOf(pages));
            MovieOperate movieOperate = new MovieOperate();
            jsonObjAmount.put("totalnum", movieOperate.getCoinMovie(username));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        jsonArray.put(jsonObjAmount);
        response.getWriter().write(jsonArray.toString());
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
